package com.caosy.grassthinkremote.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.util.Date;

@Component
public class JwtUtil {
    //Spring先执行构造方法，再注入属性
    @Value("${jwt.expiration}")
    private long jwtExpiration;//jwt过期时间

    @Value("${jwt.alias}")
    private String alias;

    @Value("${jwt.password}")
    private String password;

    private PrivateKey key;

    @Resource
    private KeyStore keyStore;

    public void setKey() throws Exception{
        this.key = (PrivateKey) keyStore.getKey(alias,password.toCharArray());//获取私钥
    }

    /**
     * 生成token
     * @param username
     * @return
     */
    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)//设置主题
                .setIssuedAt(new Date(System.currentTimeMillis()))//发布时间
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))//过期时间
                .signWith(SignatureAlgorithm.RS256,this.key)//签名通过密钥计算
                .compact();
    }


}
